<template>
    <div>
        <div class="header-container">
            <div header-left  @click="goBack">
                <i class="el-icon-arrow-left"></i>
                <button class="back-button" >返回</button>
            </div>
            <h1 class="title">个人中心</h1>
            <div class="header-right">
                <el-button type="primary" @click="handleLogout">退出登录</el-button>
            </div>
         </div>

         <!-- 内容 -->
         <div class="content">
            <div class="content-left">
                <el-upload
                    class="avatar-uploader"
                    action="http://121.37.242.119:20000/pss/images/upload"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="formData.image" :src="formData.image" class="left-ava">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                <button class="change-ava">更换头像</button>
                <span class="left-time">创建于 {{ formatDate(formData.createTime) }}</span>
                <button class="change-pwd" @click="showChangePasswordDialog = true">修改密码</button>
            </div>
            <div class="content-right">
                <div class="right-title">
                    <h3>基本信息</h3>
                    <el-button type="primary" @click="handleSubmit">保存修改</el-button>
                </div>
                <el-form ref="form" :model="formData" :rules="rules" label-width="100px">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="formData.username"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号" prop="cellPhone">
                        <el-input v-model="formData.cellPhone"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="formData.email"></el-input>
                    </el-form-item>
                    <el-form-item label="性别">
                        <el-radio-group v-model="formData.gender">
                            <el-radio :label="0">男</el-radio>
                            <el-radio :label="1">女</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="QQ" prop="qq">
                        <el-input v-model="formData.qq"></el-input>
                    </el-form-item>
                    <el-form-item label="个人介绍">
                        <el-input type="textarea" v-model="formData.intro" :rows="3"></el-input>
                    </el-form-item>
                </el-form>
            </div>
         </div>

         <!-- 修改密码对话框 -->
         <el-dialog title="重置密码" :visible.sync="showChangePasswordDialog" width="400px">
            <el-form :model="passwordForm" :rules="passwordRules" ref="passwordForm" label-width="100px">
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="passwordForm.email"></el-input>
                </el-form-item>
                <el-form-item label="验证码" prop="code">
                    <div style="display: flex;">
                        <el-input v-model="passwordForm.code" style="width: 70%;"></el-input>
                        <el-button 
                            type="primary" 
                            style="margin-left: 10px;"
                            @click="getEmailCode"
                            :disabled="isCodeButtonDisabled">
                            {{ codeButtonText }}
                        </el-button>
                    </div>
                </el-form-item>
                <el-form-item label="新密码" prop="password">
                    <el-input type="password" v-model="passwordForm.password"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input type="password" v-model="passwordForm.confirmPassword"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="showChangePasswordDialog = false">取 消</el-button>
                <el-button type="primary" @click="handleResetPassword">确 定</el-button>
            </div>
         </el-dialog>
    </div>
</template>

<script>
import axios from '../config/http'
export default {
    name: 'Personal',
    data() {
        // 确认密码的验证规则
        const validateConfirmPassword = (rule, value, callback) => {
            if (value !== this.passwordForm.password) {
                callback(new Error('两次输入的密码不一致'));
            } else {
                callback();
            }
        };
        
      return {
            formData: {
                username: '',
                cellPhone: '',
          email: '',
                gender: 0,
                qq: '',
                intro: '',
                image: '',
                createTime: '',
                userId: '',
                birthday: '',
                city: '',
                province: '',
                district: '',
                depId: null,
                job: '',
                photo: '',
                roleId: null,
                status: '',
                type: null,
                updateTime: '',
                updater: null,
                creater: null
            },
            rules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
                ],
                cellPhone: [
                    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
                ],
                email: [
                    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
                ],
                qq: [
                    { pattern: /^\d{5,11}$/, message: 'QQ号格式不正确', trigger: 'blur' }
                ],
                birthday: [
                    { pattern: /^\d{4}-\d{2}-\d{2}$/, message: '生日格式应为 YYYY-MM-DD', trigger: 'blur' }
                ],
                province: [
                    { max: 50, message: '省份名称不能超过50个字符', trigger: 'blur' }
                ],
                city: [
                    { max: 50, message: '城市名称不能超过50个字符', trigger: 'blur' }
                ],
                district: [
                    { max: 50, message: '区县名称不能超过50个字符', trigger: 'blur' }
                ],
                job: [
                    { max: 100, message: '岗位名称不能超过100个字符', trigger: 'blur' }
                ],
                intro: [
                    { max: 500, message: '个人介绍不能超过500个字符', trigger: 'blur' }
                ]
            },
            // 修改密码相关
            showChangePasswordDialog: false,
            passwordForm: {
                email: '',
                code: '',
                password: '',
                confirmPassword: '',
                type: 1,
                username: ''
            },
            passwordRules: {
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
                ],
                code: [
                    { required: true, message: '请输入验证码', trigger: 'blur' },
                    { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入新密码', trigger: 'blur' },
                    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
                ],
                confirmPassword: [
                    { required: true, message: '请再次输入新密码', trigger: 'blur' },
                    { validator: validateConfirmPassword, trigger: 'blur' }
                ]
            },
            isCodeButtonDisabled: false,
            codeButtonText: '获取验证码',
            countdown: 60
        }
    },

    methods: {
        // 获取用户信息
        async getUserInfo() {
            try {
                const result = await axios.get('/us/user/current')
                if (result.data.code === 200) {
                    const responseData = result.data.data
                    if (responseData && responseData.data) {
                        const userInfo = responseData.data
                        // 更新表单数据
                        this.formData = {
                            ...this.formData, // 保留默认值
                            ...userInfo,      // 覆盖服务器返回的值
                        }
                        
                        // 特殊处理一些字段
                        if (userInfo.gender !== undefined) {
                            this.formData.gender = Number(userInfo.gender)
                        }
                        
                        // 如果有头像，确保使用完整的URL
                        if (userInfo.image && !userInfo.image.startsWith('http')) {
                            this.formData.image = `${process.env.VUE_APP_BASE_API}${userInfo.image}`
                        }
                    } else {
                        this.$message.warning('获取用户信息数据格式异常')
                    }
                } else {
                    this.$message.error(result.data.msg || '获取用户信息失败')
                }
            } catch (error) {
                console.error('获取用户信息失败:', error)
                this.$message.error(error.response?.data?.msg || '获取用户信息失败')
            }
        },

        // 提交修改
        async handleSubmit() {
            try {
                const valid = await this.$refs.form.validate()
                if (valid) {
                    const res = await axios.put('/us/user/update', this.formData)
                    if (res.data.code === 200) {
                        this.$message.success('修改成功')
                        await this.getUserInfo() // 重新获取用户信息
                    } else {
                        this.$message.error(res.data.msg || '修改失败')
                    }
                }
            } catch (error) {
                console.error('修改用户信息失败:', error)
                this.$message.error('修改失败')
            }
        },

        // 头像上传成功
        handleAvatarSuccess(response) {
            if (response.code === 200) {
                this.formData.image = response.data
                this.$message.success('头像上传成功')
                this.handleSubmit() // 自动提交修改
            } else {
                this.$message.error(response.msg || '上传失败')
            }
        },

        // 上传前校验
        beforeAvatarUpload(file) {
            const isImage = file.type.startsWith('image/')
            const isLt2M = file.size / 1024 / 1024 < 2

            if (!isImage) {
                this.$message.error('上传头像图片只能是图片格式!')
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!')
            }
            return isImage && isLt2M
        },

        // 格式化日期
        formatDate(date) {
            if (!date) return ''
            const d = new Date(date)
            return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
        },

        // 返回
        goBack() {
      this.$router.push('/')
    },

        // 退出登录
    async handleLogout() {
            try {
        await axios.post('/as/accounts/logout')
        this.$store.dispatch('user/loginOut')
        this.$message.success('退出成功')
                this.$router.push('/login')
            } catch (error) {
                console.error('退出失败:', error)
                this.$message.error('退出失败')
            }
        },

        // 获取邮箱验证码
        async getEmailCode() {
            try {
                // 验证邮箱格式
                const emailRule = this.passwordRules.email[1];
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (!emailRegex.test(this.passwordForm.email)) {
                    this.$message.error('请输入正确的邮箱地址');
                    return;
                }

                // 发送获取验证码请求
                const res = await axios.post('/as/accounts/captcha', {
                    email: this.passwordForm.email
                },
                {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
    });

                if (res.data.code === 200) {
                    this.$message.success('验证码已发送到您的邮箱');
                    this.startCountdown();
                } else {
                    this.$message.error(res.data.msg || '获取验证码失败');
                }
            } catch (error) {
                console.error('获取验证码失败:', error);
                this.$message.error('获取验证码失败');
            }
        },

        // 开始倒计时
        startCountdown() {
            this.isCodeButtonDisabled = true;
            this.countdown = 60;
            const timer = setInterval(() => {
                if (this.countdown > 0) {
                    this.countdown--;
                    this.codeButtonText = `${this.countdown}秒后重试`;
                } else {
                    clearInterval(timer);
                    this.isCodeButtonDisabled = false;
                    this.codeButtonText = '获取验证码';
                }
            }, 1000);
        },

        // 重置密码
        async handleResetPassword() {
            try {
                const valid = await this.$refs.passwordForm.validate();
                if (valid) {
                    const res = await axios.post('/as/accounts/reset-password', {
                        email: this.passwordForm.email,
                        code: this.passwordForm.code,
                        password: this.passwordForm.password,
                        username: this.formData.username
                    });

                    if (res.data.code === 200&&res.data.data.code===200) {
                        this.$message.success('密码重置成功');
                        this.showChangePasswordDialog = false;
                        // 清空表单
                        this.$refs.passwordForm.resetFields();
                        // 退出登录，跳转到登录页
                        await this.handleLogout();
                    } else {
                        this.$message.error(res.data.msg || '密码重置失败');
                    }
                }
            } catch (error) {
                console.error('重置密码失败:', error);
                this.$message.error(error.response?.data?.msg || '重置密码失败');
            }
        }
    },

  mounted() {
    this.getUserInfo()
  }
}
</script>

<style scoped>
.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  border-bottom: 1px solid #e0e0e0;
}

.back-button {
  background-color: transparent;
  border: none;
  cursor: pointer;
  font-size: 16px;
}

.title {
  margin: 0;
  font-size: 20px;
}

.content {
    display: flex;
    width: 80%;
    justify-content: space-between;
    margin: 0 auto;
    min-height: calc(100vh - 60px);
    padding: 20px 0;
}

.content-left {
    width: 30%;
    background-color: rgb(240, 242, 243);
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 40px 20px;
    border-radius: 18px;
    height: fit-content;
}

.left-ava {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    object-fit: cover;
}

.avatar-uploader {
    margin-bottom: 20px;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 50%; 
}

.change-ava {
    margin: 15px 0;
    font-size: 16px;
    color: #409EFF;
 border: none;
    background: none;
    cursor: pointer;
}

.left-time {
    margin: 15px 0;
    font-size: 14px;
    color: #909399;
}

.change-pwd {
    margin-top: 20px;
    font-size: 16px;
    width: 100%;
    max-width: 200px;
    height: 40px;
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    background-color: white;
    cursor: pointer;
    transition: all 0.3s;
}

.change-pwd:hover {
    border-color: #409EFF;
    color: #409EFF;
}

.content-right {
    width: 65%;
    background-color: #fff;
    padding: 30px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.right-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
}

.right-title h3 {
    margin: 0;
    font-size: 20px;
    color: #303133;
}
</style>